package socket2;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){try {
        //与服务端建立连接
        System.out.println("正在连接服务端...");
        socket=new Socket("localhost",8099);//三次握手
        System.out.println("连接成功!");
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
    public void start(){
        try {
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(ow);
            PrintWriter pw = new PrintWriter(bw,true);
            Scanner sc = new Scanner(System.in);
            String message;
            while(true){
                System.out.println("请输入要发送的消息:");
                message = sc.nextLine();
                if("exit".equals(message)){
                    break;
                }else{
                    pw.println(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();//四次挥手
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args)
    {
        Client client = new Client();
        client.start();
    }

}
